package github.fafaovo.network.Packet;

import github.fafaovo.common.mycapability.ISpeedUpCapability;
import github.fafaovo.core.registry.CommonSetupEventHandler;
import github.fafaovo.example;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraft.potion.Effect;
import net.minecraft.potion.EffectInstance;
import net.minecraft.potion.Effects;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fml.network.NetworkEvent;

import java.util.List;
import java.util.function.Supplier;

public class PowerClinetForServer {



    public float power;

    public PowerClinetForServer() {
    }

    public PowerClinetForServer(float power) {
        this.power = power;
    }

    public float getPower() {
        return power;
    }

    //通过这两个函数序列化和反序列化
    public static void encode(PowerClinetForServer p, PacketBuffer buffer)
    {
        buffer.writeFloat(p.power);
    }

    public static PowerClinetForServer decode(PacketBuffer buffer)
    {
        return new PowerClinetForServer(buffer.readFloat());
    }
    //服务器处理逻辑
    public static void handlePacket(PowerClinetForServer p, Supplier<NetworkEvent.Context> context$)
    {
        NetworkEvent.Context context = context$.get();
        context.enqueueWork(()->{
            ServerPlayerEntity player = context.getSender();
            if(player != null)
            {
                LazyOptional<ISpeedUpCapability> capability = player.getCapability(CommonSetupEventHandler.SPEED_UP_CAPABILITY);
                capability.ifPresent((c)->{
                    float power1 = p.getPower();
                    c.setLevel(power1);
                    if(power1 > 100)
                    {
                        player.addPotionEffect(new EffectInstance(Effects.LUCK,60*20,1));
                    }
                    if(power1 > 200)
                    {
                        player.addPotionEffect(new EffectInstance(Effects.SPEED,60*20,1));
                    }
                    if(power1 > 300)
                    {
                        player.addPotionEffect(new EffectInstance(Effects.STRENGTH,60*20,1));
                    }
                    //example.LOGGER.info(c.getLevel());
                });
            }
        });
        context.setPacketHandled(true);
    }



}
